<template>
  <div>
    <TopFilter :list="topFilterList" :cols="4" :collapse="true" @filterChange="changeHandle" @onCollapse="collapseHandle"></TopFilter>
    <FilterTable
      ref="table"
      height="200"
      columnsRef="partPartOtherPartWaterBookIndex"
      :columns="columns"
      :fetchapi="fetchApi"
      :params="fetchParams"
      :datakey="'rows'"
      :onEnterEvent="searchHandle"
      selectionType="single"
      :onColumnsChange="columns => (this.columns = columns)"
      :onRowSelectChange="searchDetail"
    >
    </FilterTable>
    <TopFilter ref="bottomFilter" :list="inputDate1" :cols="3" :collapse="true" @filterChange="changeHandle1" @onCollapse="collapseHandle1"></TopFilter>
    <FilterTable
      ref="table"
      height="300"
      :columns="columns1"
      :fetchapi="fetchApiDetail"
      :isSelectColumn="false"
      :params="fetchParams1"
      :datakey="'rows'"
      :onColumnsChange="columns => (this.columns1 = columns)"
      :isExportExcel="true"
      exportFileName="配件流水账.xlsx"
      :onCalcExportData="exportHandle"
    >
      <template slot="controls">
        <el-button type="primary" :loading="exportBtnLoading" icon="el-icon-download" @click="handleaPullOut">导出</el-button>
      </template>
    </FilterTable>
    <BaseDialog :visible.sync="visible" :title="dialogTitle" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <BrandModal :type="handleType" :rowData="formData" @close="closeHandler" />
    </BaseDialog>
  </div>
</template>

<script>
import { dictionary } from '@/utils/dictMixin';
import { exportExcelFile } from '@/utils';
import { searchPartWaterByDto, searchPartWaterDetail, exportData } from '@/api/part/partOther/partWaterBook';
import BrandModal from './tabs/brandModal';
import { getEmployeeInfo } from '@/api/common/auth/employeeAuth';
import { getAllUser } from '@/api/customerRepair/afterSaleVisit/resultEntry';
import moment from 'moment';
import { findAllRepair } from '@/api/repair/basicParameters';
import { getStroageList } from '@/api/part/partOutbound/partBreak';
import { findStorageCode } from '@/api/common/auth/roleManage/index.js';

export default {
  name: 'Brand',
  components: {
    BrandModal
  },
  mixins: [dictionary],
  data() {
    this.conf = { add: '新增', edit: '编辑', show: '显示' };
    return {
      js: {
        partNo: '',
        storageCodeName: ''
      },
      topFilterList: this.createTopFilterList(),
      inputDate1: this.inputDate(),
      fetchParams: { xhrAbort: true },
      fetchParams1: { xhrAbort: true },
      visible: false,
      dialogTitle: '',
      fetchApi: searchPartWaterByDto,
      fetchApiDetail: searchPartWaterDetail,
      columns: this.createTableColumns(),
      columns1: this.createTableColumns1(),
      handleType: '',
      formData: {},
      serviceAdvisorData: [],
      storageName: [],
      searchBeginDate: moment(new Date().setDate(1)).format('YYYY-MM-DD') + ' 00:00:00',
      nowTime: moment(new Date()).format('YYYY-MM-DD HH:mm:ss'),
      exportBtnLoading: false // 导出按钮是否加载
    };
  },
  mounted() {
    this.getQueryBookingInformation();
    this.BaseTable = this.$refs.table.$refs.pageTable;
    this.getStorageList();
    // this.searchBeginDate.setDate(1);
    this.inputDate1[this.findIndex(this.inputDate1, 'start|end')].initialValue = [this.searchBeginDate, this.nowTime];
  },
  methods: {
    // 导出行数据处理
    exportHandle(row) {
      for (const key in row) {
        if (row.hasOwnProperty(key)) {
          let element = row[key];
          if (!isNaN(row[key])) {
            if (key == 'license') {
              return;
            } else if (key == 'index') {
              return;
            } else if (key == 'customerName') {
              return;
            }
            row[key] = Number(row[key]).toFixed(2);
          }
        }
      }
    },
    findIndex(arr, fieldName) {
      let indexR = -1;
      arr.forEach((x, index) => {
        if (x.fieldName == fieldName) {
          indexR = index;
        }
      });
      return indexR;
    },
    inputDate() {
      return [
        {
          type: 'RANGE_DATE',
          label: '查看日期',
          fieldName: 'start|end',
          placeholder: '查看日期',
          dateType: 'daterange'
        },
        {
          type: 'SELECT',
          label: '进出类型',
          fieldName: 'inOutType',
          filterable: true,
          placeholder: '请输入...',
          itemList: this.createDictList(8249, [82491008, 82491025, 82491026, 82491027, 82491028, 82491029, 82491018, 82491016, 82491017, 82491003, 82491012, 82491024, 82491015])
        }
      ];
    },
    createTopFilterList() {
      return [
        {
          type: 'SELECT',
          label: '仓库',
          fieldName: 'storageCode',
          placeholder: '请输入...',
          itemList: []
        },
        {
          type: 'INPUT',
          label: '配件代码',
          fieldName: 'partNo',
          placeholder: '请输入...'
        },
        {
          type: 'INPUT',
          label: '配件名称',
          fieldName: 'partName',
          placeholder: '请输入...'
        }
      ];
    },
    createTableColumns() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 70,
          sorter: true,
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        // {
        //   title: '经销商简称',
        //   dataIndex: 'ownerCode',
        //   sorter: true,
        //   filter: true,
        //   filterType: 'input'
        // },
        {
          title: '仓库',
          dataIndex: 'storageCode',
          sorter: true,
          filter: true,
          filterType: 'input',
          render: props => {
            return <span>{this.getStorageName(props.row.storageCode)}</span>;
          },
          showOverflowTooltip: true
        },
        {
          title: '库位',
          dataIndex: 'storagePositionCode',
          sorter: true,
          filter: true,
          filterType: 'input',
          showOverflowTooltip: true
        },
        {
          title: '配件代码',
          dataIndex: 'partNo',
          sorter: true,
          filter: true,
          filterType: 'input',
          showOverflowTooltip: true
        },
        {
          title: '配件名称',
          dataIndex: 'partName',
          sorter: true,
          filter: true,
          filterType: 'input',
          showOverflowTooltip: true
        },
        {
          title: '计量单位',
          dataIndex: 'unitName',
          sorter: true,
          filter: true,
          filterType: 'input',
          showOverflowTooltip: true
        },
        {
          title: '库存数量',
          dataIndex: 'stockQuantity',
          sorter: true,
          precision: 2,
          filter: true,
          filterType: 'number',
          showOverflowTooltip: true
        },
        {
          title: '锁定数量',
          dataIndex: 'lockedQuantity',
          sorter: true,
          precision: 2,
          filter: true,
          filterType: 'number'
        },
        // {
        //   title: '借入数量',
        //   dataIndex: 'borrowQuantity',
        //   sorter: true,
        //   precision: 2,
        //   filter: true,
        //   filterType: 'number'
        // },
        {
          title: '可用库存',
          dataIndex: 'useableStock',
          sorter: true,
          filter: true,
          precision: 2,
          filterType: 'number',
          showOverflowTooltip: true
        },
        {
          title: '最新入库日期',
          dataIndex: 'lastStockIn',
          sorter: true,
          filter: true,
          filterType: 'date-range',
          showOverflowTooltip: true
        },
        {
          title: '最新出库日期',
          dataIndex: 'lastStockOut',
          sorter: true,
          filter: true,
          filterType: 'date-range',
          showOverflowTooltip: true
        }
      ];
    },
    createTableColumns1() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 70,
          sorter: true,
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '发生日期',
          dataIndex: 'operateDate',
          width: 150,
          sorter: true,
          filter: true,
          filterType: 'date-range',
          showOverflowTooltip: true
        },
        {
          title: '进出类型',
          dataIndex: 'inOutType',
          sorter: true,
          filter: true,
          filterType: 'checkbox',
          filterItems: this.createDictList('8249', [82491008, 82491025, 82491026, 82491027, 82491028, 82491029, 82491018, 82491016, 82491017, 82491003, 82491012, 82491015]),
          dictItems: this.createDictList('8249'),
          render: (props, h) => {
            return <span> {this.createDictText(props.row.inOutType, '8249')} </span>;
          },
          showOverflowTooltip: true
        },
        {
          title: '进数量',
          dataIndex: 'stockInQuantity',
          sorter: true,
          filter: true,
          precision: 2,
          filterType: 'number',
          showOverflowTooltip: true
        },
        {
          title: '出数量',
          dataIndex: 'stockOutQuantity',
          sorter: true,
          filter: true,
          precision: 2,
          filterType: 'number',
          showOverflowTooltip: true
        },
        {
          title: '出入不含税单价',
          dataIndex: 'inOutNetPrice',
          sorter: true,
          filter: true,
          precision: 2,
          filterType: 'number',
          showOverflowTooltip: true
        },
        {
          title: '出入不含税金额',
          dataIndex: 'inOutNetAmount',
          sorter: true,
          filter: true,
          precision: 2,
          filterType: 'number',
          showOverflowTooltip: true
        },
        {
          title: '出入库含税单价',
          dataIndex: 'inOutTaxedPrice',
          sorter: true,
          filter: true,
          precision: 2,
          filterType: 'number',
          showOverflowTooltip: true
        },
        {
          title: '出入库含税金额',
          dataIndex: 'inOutTaxedAmount',
          sorter: true,
          filter: true,
          precision: 2,
          filterType: 'number',
          showOverflowTooltip: true
        },
        {
          title: '入账后库存数量',
          dataIndex: 'stockQuantity',
          sorter: true,
          filter: true,
          precision: 2,
          filterType: 'number',
          showOverflowTooltip: true
        },
        {
          title: '含税成本单价',
          dataIndex: 'costPrice',
          sorter: true,
          filter: true,
          precision: 2,
          filterType: 'number',
          showOverflowTooltip: true
        },
        {
          title: '含税成本金额',
          dataIndex: 'costAmount',
          sorter: true,
          filter: true,
          precision: 2,
          filterType: 'number',
          showOverflowTooltip: true
        },
        {
          title: '车牌号',
          dataIndex: 'license',
          sorter: true,
          filter: true,
          filterType: 'input',
          showOverflowTooltip: true
        },
        {
          title: '单据号码',
          dataIndex: 'sheetNo',
          sorter: true,
          filter: true,
          filterType: 'input',
          showOverflowTooltip: true
        },
        {
          title: '客户名称',
          dataIndex: 'customerName',
          sorter: true,
          filter: true,
          filterType: 'input',
          showOverflowTooltip: true
        },
        {
          title: '操作员',
          dataIndex: 'createdBy',
          sorter: true,
          filterType: 'input',
          dictItems: [],
          render: props => {
            return <span>{this.getEmployeeName(props.row.createdBy)}</span>;
          },
          showOverflowTooltip: true
        }
      ];
    },
    async getQueryBookingInformation() {
      let res = await getAllUser();
      this.serviceAdvisorData = res.data.map(x => ({ text: x.employeeName, value: x.userId }));
      // 导出翻译人名
      this.columns1.find(x => x.dataIndex == 'createdBy').dictItems = this.serviceAdvisorData;
    },
    getEmployeeName(userId) {
      const item = this.serviceAdvisorData.find(x => {
        return x.value == userId;
      });
      return item ? item.text : '';
    },
    getStorageName(storageCode) {
      const item = this.storageName.find(x => {
        return x.value == storageCode;
      });
      return item ? item.text : '';
    },
    inOutQuantity(val) {
      if (val == null) return 0.0;
      else return val;
    },
    addHandle() {
      this.handleType = 'add';
      this.showHandler();
    },
    editHandle(row) {
      this.handleType = 'edit';
      this.formData = row;
      this.showHandler();
    },
    changeHandle(val) {
      this.fetchParams = Object.assign({}, val);
    },
    searchDetail(row) {
      if (row.length > 0) {
        this.js = row[0];
      }
    },
    collapseHandle() {
      this.$nextTick(() => {
        this.BaseTable.EXECUTE_RESET_HEIGHT();
      });
    },
    collapseHandle1() {
      this.$nextTick(() => {
        this.BaseTable.EXECUTE_RESET_HEIGHT();
      });
    },
    async searchHandle() {
      let data = await this.$refs.bottomFilter.GET_FORM_DATA();
      let val = {
        start: data[1].start,
        end: data[1].end,
        inOutType: data[1].inOutType
      };
      console.log(val, 'bottomFilter');
      this.changeHandle1(val);
    },
    changeHandle1(val) {
      if (val.start) {
        val.start = moment(val.start).format('YYYY-MM-DD');
      }
      if (val.end) {
        val.end = moment(val.end).format('YYYY-MM-DD');
      }
      let data = {
        start: val.start,
        end: val.end,
        partNo: this.js.partNo,
        inOutType: val.inOutType,
        storageCodeName: this.js.storageCode
      };
      this.fetchParams1 = Object.assign({}, data);
    },
    showHandler() {
      this.dialogTitle = `${this.conf[this.handleType]}品牌`;
      this.visible = true;
    },
    closeHandler(val, type) {
      this.visible = val;
      if (type === 'refresh') {
        // 重新加载
        this.fetchParams = { ...this.fetchParams };
      }
    },
    async getStorageList() {
      // let resdata = await findAllRepair();
      let res = (await findStorageCode()).data.map(x => ({ text: x.STORAGE_NAME, value: x.STORAGE_CODE }));
      this.storageName = res;
      let res1 = (await getStroageList()).data.map(x => ({ text: x.STORAGE_NAME, value: x.STORAGE_CODE }));
      // this.topFilterList.find(item => item.fieldName === 'storageCode').initialValue = resdata.data['1100'];
      this.topFilterList.find(item => item.fieldName === 'storageCode').itemList = res1;
    },
    // 点击导出
    async handleaPullOut() {
      if (this.js.partNo) {
        if (this.exportBtnLoading) return;
        this.exportBtnLoading = true;
        let queryData = (await this.$refs.bottomFilter.GET_FORM_DATA())[1];
        queryData.start = queryData.start ? moment(queryData.start).format('YYYY-MM-DD') : '';
        queryData.end = queryData.end ? moment(queryData.end).format('YYYY-MM-DD') : '';
        let data = {
          // ...queryData,
          start: queryData.start,
          end: queryData.end,
          partNo: this.js.partNo,
          storageCodeName: this.js.storageCode
        };
        let res = await exportData(data);
        this.exportBtnLoading = false;
        exportExcelFile(res.data, this.js.partName + '在仓库' + this.getStorageName(this.js.storageCode) + '中流水账导出');
      }
    }
  }
};
</script>

<style lang="less" scoped></style>
